/*
 * @Description: 
 * @Author: duan_shuangjun 丶
 * @Date: 2025-08-20 17:21:46
 * @LastEditTime: 2025-09-25 21:35:49
 */
import { defineStore } from 'pinia'
import { LocalStorage } from '@/utils/storage'
import { fetchUserInfo } from '@/api/user'
import { deskWorkStatus } from '@/api/desktop'
import { initWebSocketModule } from '@/webSocket/init'
export interface UserInfo {
  id?: number | string
  name?: string
  avatar?: string
  roles?: string[]
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '' as string,
    avatar: '' as string,
    name: '' as string,
    userId: '' as string | number,
    roles: [] as string[],
    userInfo: {} as Record<string, any>,
    shopInfo: {} as Record<string, any>,
    desktopWorkStatus: null as null | number,
    currentSlot: null as null | string,
    currentRoutePath: '' as string,
    networkStatus: 'online' as 'online' | 'offline',
    shopWorkStatus: null as null | number
  }),
  actions: {
    setToken(token: string) { this.token = token },
    setUserInfo(info: Partial<UserInfo>) { this.userInfo = { ...this.userInfo, ...info } },
    setShopInfo(info: Record<string, any>) { this.shopInfo = info },
    setCurrentRoute(path: string) { this.currentRoutePath = path },
    setNetworkStatus(status: 'online' | 'offline') { this.networkStatus = status },

    async initLoadUserProfile() {
      try {
        await this.loadUserProfile()
        await this.fetchDeskWorkStatus()
        initWebSocketModule()

      } catch (error) {
        console.error('初始化用户数据失败:', error)
        // 如果是网络错误或认证错误，抛出错误让上层处理
        if (error?.response?.status === 401 || error?.code === 'NETWORK_ERROR') {
          throw error
        }
        // 其他错误继续执行，不阻断应用启动
      }
    },

    async loadUserProfile() {
      // 避免重复请求：有缓存直接返回
      // if (this.userInfo && Object.keys(this.userInfo).length > 0 && this.shopInfo && Object.keys(this.shopInfo).length > 0) {
      //   return { userInfo: this.userInfo, shopInfo: this.shopInfo }
      // }
      const userId: string = LocalStorage.get('userId') || ''
      const res: any = await fetchUserInfo(userId)
      if (res?.status === 200) {
        this.userInfo = res?.data?.userInfo || {}
        this.shopInfo = res?.data?.shopInfo || {}
        // this.shopWorkStatus = res?.data?.shopWorkStatus ?? this.shopWorkStatus
      }
      return res
    },

    // 获取当前店铺班次信息
    async fetchDeskWorkStatus() {
      if (!LocalStorage.get('token')) return
      const ws: any = await deskWorkStatus({})
      if (ws?.status === 200) {
        this.desktopWorkStatus = ws?.data?.status ?? this.desktopWorkStatus
        this.currentSlot = ws?.data?.current_slot ?? this.currentSlot
        this.shopWorkStatus = ws?.data?.shop_status ?? this.shopWorkStatus
      }
      return ws
    },



    logout() {
      this.token = ''
      this.userInfo = {}
      this.shopInfo = {}
      LocalStorage.remove('token')
    }
  }
})
